﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using StyleCop.CSharp;

namespace StyleCop.Extensions
{
    [SourceAnalyzer(typeof(CsParser))]
    public class MethodParameterPUnderscorePrefix : SourceAnalyzer
    {
        public override void AnalyzeDocument(CodeDocument document)
        {
            CsDocument csdocument = (CsDocument)document;

            if (csdocument.RootElement != null && !csdocument.RootElement.Generated)
                csdocument.WalkDocument(new CodeWalkerElementVisitor<object>(this.VisitElement), null, null);
        }


        private bool VisitElement(CsElement element, CsElement parentElement, object context)
        {
            // Flag a violation if the instance variables are not prefixed with an underscore.
            if (!element.Generated &&
                (element.ElementType == ElementType.Method
                || element.ElementType == ElementType.Constructor
                || element.ElementType == ElementType.Indexer
                || element.ElementType == ElementType.Delegate
                ))
            {
                IList<Parameter> parameters = null;

                if (element.ElementType == ElementType.Constructor)
                {
                    parameters = ((Constructor)element).Parameters;
                }
                else if (element.ElementType == ElementType.Delegate)
                {
                    parameters = ((StyleCop.CSharp.Delegate)element).Parameters;
                }
                else if (element.ElementType == ElementType.Method)
                {
                    parameters = ((Method)element).Parameters;
                }
                else if (element.ElementType == ElementType.Indexer)
                {
                    parameters = ((Indexer)element).Parameters;
                }

                if (parameters != null)
                {
                    foreach (var item in parameters)
                    {
                        // If argument type is 'EventArgs' allow non-Camel case variable name also.
                        if (!item.Type.Text.ToLower().EndsWith("EventArgs".ToLower()))
                        {
                            if (!item.Name.StartsWith("P_"))
                                AddViolation(element, Rules.MethodParameterPUnderscorePrefix);
                        }
                    }
                }
            }

            return true;
        }
    }
}
